package filters;

import backingbeans.UserSession;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
public class LoginFilter implements Filter {
    @Inject
    private UserSession userSession;
    private static final String LOGIN_URL1 = "/faces/index.xhtml";
    private static final String LOGIN_URL2 = "/";
    private static final String LISTSONGS_URL = "/faces/listallsongs.xhtml";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        
        // Not logged and requested web page is not the login page so redirect
        if ((userSession == null || !userSession.isConnected() || userSession.getUser() == null) 
                && !requestURI.equals(request.getServletContext().getContextPath() + LOGIN_URL1) 
                && !requestURI.equals(request.getServletContext().getContextPath() + LOGIN_URL2)) {

            // Redirect to the login page
            ((HttpServletResponse) response).sendRedirect(request.getServletContext().getContextPath() + LOGIN_URL2); 
        } 
        // Logged in but current page is login page
        else if(userSession != null && userSession.isConnected() && userSession.getUser() != null 
                && (requestURI.equals(request.getServletContext().getContextPath() + LOGIN_URL1) 
                || requestURI.equals(request.getServletContext().getContextPath() + LOGIN_URL2))) { 
            // Redirect to the list page
            ((HttpServletResponse) response).sendRedirect(request.getServletContext().getContextPath() + LISTSONGS_URL); 
        }
        // Other cases : Logged in and not in login page
        //               Not logged in and in the login page
        else { 
            chain.doFilter(request, response); 
        }
        
    }

    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
